﻿var pager;
var menu;
var grid;
var tree;
var dataSource;
var splitter;
var splitterWidth = "200px";
var selectedTree = true;
var queryUnselectTree = true;
var query = {};
query.pageSize = 20;
query.pageNo = 1;

jQuery(function ()
{
    //分栏
    if (typeof leftWidth != "undefined")
    {
        splitterWidth = leftWidth;
    }
    var height = $("body").height() - $("#operate").height();
    $("#lay-tree").height(height);
    splitter = $("#lay-tree").kendoSplitter(
    {
        panes:
        [
        { collapsible: true, size: splitterWidth },
        { collapsible: false }
        ]
    }).data("kendoSplitter");

    //树
    tree = $("#tree").data("kendoTreeView");
    dataSource = tree.dataSource;

    //搜索
    $("body").click(function ()
    {
        $("#advance").hide();
    });
    $("#advance").click(function (event)
    {
        event.stopPropagation();
    });
    $(".k-popup").click(function (event)
    {
        $("body").unbind("click");
    });
    $(".k-popup").mouseout(function (event)
    {
        $("body").click(function ()
        {
            $("#advance").hide();
        });
    });
    $("#keyword").next("button").click(function (event)
    {
        event.stopPropagation();
        $("#advance").toggle();
    });
    $("#keyword").find(".k-i-search").click(function ()
    {
        searchKeyword();
    });
    $("#keyword").find(":text").keydown(function (e)
    {
        if (e.keyCode == 13)
        {
            searchKeyword();
            return false;
        }
    });
    $("#advance").find(":button").click(function ()
    {
        searchAdvance();
    });
    $("#advance").keydown(function (e)
    {
        if (e.keyCode == 13)
        {
            searchAdvance();
        }
    });
    $("#advance").find(":reset").click(function ()
    {
        searchReset();
    });

    //右键菜单
    menu = $("#menu").kendoMenu().data("kendoMenu");

    //分页
    pager = jQuery("#pager").kendoPager(
    {
        messages:
        {
            display: "第{0}-{1}项 总计{2}项",
            empty: "总计0项",
            page: "页",
            of: "第{0}",
            itemsPerPage: "项每页",
            refresh: "刷新",
            first: "首页",
            previous: "上页",
            next: "下页",
            last: "未页"
        },

        change: function (e)
        {
            query.pageNo = e.index;
            reload();
        }
    }).data("kendoPager");
});

function bind(result)
{
    var total = resultHelper.total(result);
    var html = resultHelper.html(result);

    //构造分页
    var dataSource = new kendo.data.DataSource(
    {
        data: new Array(total),
        pageSize: query.pageSize,
        page: query.pageNo
    });
    pager.setDataSource(dataSource);
    pager.refresh();

    //构造表格
    $("#grid").html(html);
    var ids = [];
    var widths = [];
    $("#grid").find("th").each(function ()
    {
        var field = $(this).attr("data-field");
        if (!field)
        {
            $(this).attr("data-field", $(this).text().trim());
        }
        else
        {
            field = field.replace(".", "_");
            $(this).attr("data-field", field)
            $(this).addClass("orderby");
        }
        widths.push($(this).attr("width"));

        if (query.orderBy)
        {
            if (query.orderBy.replace(".", "_") == field)
            {
                $(this).html($(this).text() + '<span class="k-icon k-i-arrow-n"></span>');
            }
            else if (query.orderBy.replace(".", "_") == field + " DESC")
            {
                $(this).html($(this).text() + '<span class="k-icon k-i-arrow-s"></span>');
            }
        }
    });
    $("#grid").find("tbody tr").each(function ()
    {
        ids.push($(this).attr("id"));
    });
    var height = $("body").height() - $("#operate").height() - 35;
    grid = $("#grid").find("table").kendoGrid(
        {
            selectable: "multiple",
            height: height
        }).data("kendoGrid");
    $.each(widths, function (index, item)
    {
        if (item) $("#grid").find("tbody tr td:eq(" + index + ")").width(item);
    });
    $("#grid").find("tbody tr").each(function (i)
    {
        $(this).attr("id", ids[i])
    });
    $("#grid").find("tbody tr").dblclick(function ()
    {
        if (window.dbclick)
        {
            window.dbclick();
        }
        else if (window.detail)
        {
            window.detail();
        }
        else if (window.items)
        {
            window.items();
        }
        else if (window.modify)
        {
            window.modify();
        }
    });
    $("#grid").find("tbody tr").bind('contextmenu', function (e)
    {
        //当菜单超出窗口边界时处理
        var left = e.pageX;
        var top = e.pageY;
        var p =
            {
                wh: $("body").height(),
                ww: $("body").width(),
                mh: $("#menu").height(),
                mw: $("#menu").width()
            };
        left = (left + p.mw) >= p.ww ? (left -= p.mw) : left;
        top = (top + p.mh) >= p.wh ? (top -= p.mh) : top;
        $("#menu").css(
            {
                zIndex: 10000,
                left: left,
                top: top
            });
        $("#menu").show();
        menu.open(".k-first");

        //选中
        grid.clearSelection();
        grid.select(this);

        return false;
    });

    $("#grid").find(".orderby").click(function ()
    {
        var field = $(this).attr("data-field").replace("_", ".");
        if (query.orderBy == field)
        {
            query.orderBy = field + " DESC";
        }
        else
        {
            query.orderBy = field;
        }
        reload();
    });
}

function bindList(result)
{
    var total = resultHelper.total(result);
    var html = resultHelper.html(result);

    //构造分页
    var dataSource = new kendo.data.DataSource(
        {
            data: new Array(total),
            pageSize: query.pageSize,
            page: query.pageNo
        });
    pager.setDataSource(dataSource);
    pager.refresh();

    //构造表格
    $("#grid").attr("class", "list");
    $("#grid").html("<div class='wrap'>" + html + "</div>");
    var height = $("body").height() - $("#operate").height() - 35;
    $("#grid").height(height);

    $("#grid").find(".item").click(function (e)
    {
        if (e.ctrlKey)
        {
            $(this).addClass("k-state-selected");
        }
        else if (e.shiftKey)
        {
            var from = $("#grid .item").index(this);
            var to = $("#grid .item.k-state-selected").index();
            if (to == -1)
            {
                $("#grid").find(".item").removeClass("k-state-selected");
                $(this).addClass("k-state-selected");
            }
            else
            {
                $("#grid").find(".item").removeClass("k-state-selected");
                var begin = from < to ? from : to;
                var end = from < to ? to : from;
                for (var i = begin; i <= end; i++)
                {
                    $("#grid .item").eq(i).addClass("k-state-selected");
                }
            }
        }
        else
        {
            $("#grid").find(".item").removeClass("k-state-selected");
            $(this).addClass("k-state-selected");
        }
    });

    $("#grid").find(".item").dblclick(function ()
    {
        if (window.dbclick)
        {
            window.dbclick();
        }
        else if (window.detail)
        {
            window.detail();
        }
        else if (window.items)
        {
            window.items();
        }
        else if (window.modify)
        {
            window.modify();
        }
    });
    $("#grid").find(".item").bind('contextmenu', function (e)
    {
        //当菜单超出窗口边界时处理
        var left = e.pageX;
        var top = e.pageY;
        var p =
            {
                wh: $("body").height(),
                ww: $("body").width(),
                mh: $("#menu").height(),
                mw: $("#menu").width()
            };
        left = (left + p.mw) >= p.ww ? (left -= p.mw) : left;
        top = (top + p.mh) >= p.wh ? (top -= p.mh) : top;
        $("#menu").css(
            {
                zIndex: 10000,
                left: left,
                top: top
            });
        $("#menu").show();
        menu.open(".k-first");

        //选中
        $("#grid").find(".item").removeClass("k-state-selected");
        $(this).addClass("k-state-selected");

        return false;
    });
}

function searchKeyword()
{
    if (queryUnselectTree)
    {
        nodeUnselect();
    }

    var form = $("#advance").find("form");
    var input = $("#keyword").find(":text");
    var params = input.attr("name") + "=" + input.val();
    var pageSize = query.pageSize;
    var orderBy = query.orderBy;

    form[0].reset();
    query = paramsToObject(params);
    query.pageNo = 1;
    query.pageSize = pageSize;
    query.orderBy = orderBy;
    reload();
}

function searchAdvance()
{
    if (queryUnselectTree)
    {
        nodeUnselect();
    }

    var form = $("#advance").find("form");
    var input = $("#keyword").find(":text");
    var pageSize = query.pageSize;
    var orderBy = query.orderBy;

    input.val("");
    query = form.serializeObject();
    query.pageNo = 1;
    query.pageSize = pageSize;
    query.orderBy = orderBy;
    reload();
}

function searchReset()
{
    if (queryUnselectTree)
    {
        nodeUnselect();
    }

    searchClear();
    setTimeout(function ()
    {
        reload();
    }, 1)
}

function searchClear()
{
    var form = $("#advance").find("form");
    var input = $("#keyword").find(":text");
    var pageSize = query.pageSize;
    var orderBy = query.orderBy;

    if ($("#keyword").length != 0)
    {
        input.val("");
    }
    if ($("#advance").length != 0)
    {
        form[0].reset();
        query = {};
    }
    query.pageNo = 1;
    query.pageSize = pageSize;
    query.orderBy = orderBy;
}

function gridSelected()
{
    var ids = [];
    $("#grid").find(".k-state-selected").each(function ()
    {
        ids.push($(this).attr("id"));
    });
    if (ids.length == 0)
    {
        return null;
    }
    return ids;
}

function gridSelectedHidden(name)
{
    var datas = [];
    $("#grid").find(".k-state-selected :hidden[name='" + name + "']").each(function ()
    {
        datas.push($(this).val());
    });
    if (datas.length == 0)
    {
        return null;
    }
    return datas;
}

function nav(url)
{
    top.navTab(url);
}

function back(reload, data, message, delay)
{
    top.backTab(reload, data, message, delay)
}

function reload(data)
{
    read();
}

function readTree(option, model)
{
    if (typeof (option.selected) != 'undefined')
    {
        selectedTree = option.selected;
    }
    var modelTree = { children: "childs" };
    if (typeof (option.model) != 'undefined')
    {
        modelTree = option.model;
    }
    $("#tree").kendoTreeView(
    {
        dataSource:
        {
            transport: { read: option.url },
            schema:
            {
                data: "Data",
                model: modelTree,
                errors: "Errors"
            },
            error: function (e)
            {
                alert(e.errors);
            }
        },
        dataBound: onDataBound,
        select: onSelect,
        dragend: onDragend
    });
}

function reloadTree(data)
{
    //如果是重载
    if (!data)
    {
        dataSource.read();
        return;
    }

    //如果是删除
    if (!data.id)
    {
        var item = dataSource.get(data);
        var node = tree.findByUid(item.uid);
        tree.remove(node);

        //返回父级节点
        var parentItem = item.parentNode();
        if (parentItem)
        {
            nodeSelect(parentItem.id);
            return;
        }

        //返回同级第一节点
        var items = dataSource.data();
        if (items.length > 0)
        {
            nodeSelect(items[0].id);
            return;
        }

        return;
    }

    //如果是新增
    var item = dataSource.get(data.id);
    if (item == null)
    {
        var parentItem = dataSource.get(data.parentId);
        if (parentItem)
        {
            var parentNode = tree.findByUid(parentItem.uid);
            tree.append({ id: data.id, text: data.text }, parentNode);
        }
        else
        {
            tree.append({ id: data.id, text: data.text });
        }

        nodeSelect(data.id);
        return;
    }

    var parentItemOld = item.parentNode();
    var parentIdOld = parentItemOld == null ? null : parentItemOld.id;
    var node = tree.findByUid(item.uid);

    //如果是修改
    if (parentIdOld == data.parentId)
    {
        tree.text(node, data.text);
        nodeSelect(data.id);
        return;
    }

    //如果是修改并移动
    var parentItem = dataSource.get(data.parentId);
    tree.remove(node);
    if (parentItem)
    {
        var parentNode = tree.findByUid(parentItem.uid);
        tree.append({ id: data.id, text: data.text }, parentNode);
    }
    else
    {
        tree.append({ id: data.id, text: data.text });
    }

    nodeSelect(data.id);
}

function nodeSelect(id)
{
    var item = dataSource.get(id);
    var node = tree.findByUid(item.uid);
    tree.select(node);
    tree.selectedId = id;
    reload();
}

function nodeUnselect()
{
    tree.select().find(".k-in").removeClass("k-state-focused");
    tree.select().find(".k-in").removeClass("k-state-selected");
    tree.selectedId = null;
}

function treeSelected()
{
    return tree.selectedId;
}

function onDataBound(e)
{
    if (e.node) return;
    if (selectedTree)
    {
        var items = dataSource.data();
        if (items.length == 0) return;
        if (items.length == 1)
        {
            var node = tree.findByUid(items[0].uid);
            tree.expand(node);
        }
        nodeSelect(items[0].id);
    }
    else
    {
        reload();
    }
}

function onSelect(e)
{
    searchClear();

    $(e.node).find(".k-in").addClass("k-state-selected");
    var item = dataSource.getByUid($(e.node).attr("data-uid"));
    tree.selectedId = item.id;

    reload();
}

function onDragend(e)
{
    var sourceItem = dataSource.getByUid($(e.sourceNode).attr("data-uid"));
    var destinationItem = dataSource.getByUid($(e.destinationNode).attr("data-uid"));
    move(sourceItem.id, destinationItem.id, e.dropPosition);
}